import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from "vue-router";
import employeesrouter from "../router/modules/employees";
import settingsrouter from "../router/modules/settings";
import permissionsrouter from "../router/modules/permissions";
import social_securitysrouter from "../router/modules/social_securitys";
import approvalsrouter from "../router/modules/approvals";
import attendancesrouter from "../router/modules/attendances";
import store from "../store";
import Cookies from "js-cookie";
import { tranRoute } from "../utils/routeIng";

// 动态路由
export const asyncroute = [
  employeesrouter,
  settingsrouter,
  permissionsrouter,
  social_securitysrouter,
  approvalsrouter,
  attendancesrouter,
];
// 静态
export const routes = [
  {
    path: "/logins", //vue3基本语法演示
    name: "logins",
    component: () => import("../views/logins.vue"),
  },
  //根目录,到登录页面
  {
    path: "/index",
    component: () => import("../views/users/index.vue"),
    name: "home",
    children: [
      {
        path: "/", //vue3基本语法演示
        name: "dashboard",
        component: () => import("../views/dashboard/index.vue"),
        meta: { title: "首页", icon: "dashboard" },
      },
    ],
  },
];

export const router = createRouter({
  history: createWebHashHistory(), // hash模式：createWebHashHistory，history模式：createWebHistory
  routes: [ ...routes],
  // routes,
});
// 路由拦截

router.beforeEach(async (to, from, next) => {
  if (Cookies.get("token")) {
    if (!store.state.userInfo) {
      //是否可以拿到用户得基本信息
      console.log(router);
      let menusList = await store.dispatch("user/menus");
      store.dispatch("user/filteruser", menusList).then((res) => {
        console.log(res);
        let arr = tranRoute(res);
        console.log(arr);
        console.log(store.state);
        arr.forEach(item => {
          router.addRoute('home', item)
        })
      });
    
      next();
    } else {
      next();
    }
  } else {
    if (to.path == "/logins") {
      next();
    } else {
      next("/logins");
    }
  }
});

export default router;
